<template>
  <div
    class="layer-item bg-white border border-gray-200 rounded-md p-3 flex items-center hover:shadow-md transition-all"
    :class="{
      'bg-gray-100': layer.locked,
      'opacity-60': !layer.visible,
    }"
    @contextmenu="$emit('contextmenu', $event)"
  >
    <!-- 拖拽手柄 -->
    <q-icon
      name="drag_indicator"
      class="drag-handle mr-2 text-gray-400 cursor-move"
      size="sm"
    />

    <!-- 图层类型图标 -->
    <div class="relative group">
      <q-icon :name="layerIcons[layer.type]" class="text-blue-500" size="sm" />
      <div
        class="tooltip absolute bottom-full left-1/2 transform -translate-x-1/2 bg-black text-white text-xs px-2 py-1 rounded mb-1 opacity-0 group-hover:opacity-100 transition-opacity"
      >
        {{ layerTypeLabels[layer.type] }}
      </div>
    </div>

    <!-- 图层名称 -->
    <div class="ml-3 flex-1 min-w-0">
      <q-input
        v-if="isRenaming"
        v-model="tempName"
        dense
        autofocus
        @keyup.enter="confirmRename"
        @blur="confirmRename"
      />
      <div
        v-else
        class="truncate text-gray-800"
        :class="{ 'text-gray-400': layer.locked }"
      >
        {{ layer.name }}
      </div>
    </div>

    <!-- 图层操作 -->
    <div class="flex space-x-2 ml-2">
      <q-btn
        flat
        dense
        round
        size="sm"
        :icon="layer.visible ? 'visibility' : 'visibility_off'"
        :color="layer.visible ? 'primary' : 'gray'"
        @click="$emit('toggle-visibility', layer.id)"
      />
      <q-btn
        flat
        dense
        round
        size="sm"
        :icon="layer.locked ? 'lock' : 'lock_open'"
        :color="layer.locked ? 'primary' : 'gray'"
        @click="$emit('toggle-lock', layer.id)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { Layer } from "./DragTree.vue";

const props = defineProps<{
  layer: Layer;
}>();

const emit = defineEmits([
  "rename",
  "toggle-visibility",
  "toggle-lock",
  "contextmenu",
]);

// 图层类型图标映射
const layerIcons = {
  container: "widgets",
  component: "extension",
  shape: "crop_square",
  text: "text_fields",
  chart: "bar_chart",
};

const layerTypeLabels = {
  container: "容器",
  component: "组件",
  shape: "形状",
  text: "文字",
  chart: "图表",
};

// 重命名功能
const isRenaming = ref(false);
const tempName = ref("");

function initiateRename() {
  isRenaming.value = true;
  tempName.value = props.layer.name;
}

function confirmRename() {
  if (tempName.value.trim() !== props.layer.name) {
    emit("rename", props.layer.id, tempName.value.trim());
  }
  isRenaming.value = false;
}

// 暴露重命名方法给父组件
defineExpose({
  initiateRename,
});
</script>

<style scoped>
.layer-item {
  transition: all 0.2s ease;
}

.tooltip {
  white-space: nowrap;
  pointer-events: none;
  z-index: 100;
}
</style>
